<template>
	<el-card shadow="hover" class="query-form-card">
		<template #header>
			<div class="card-header">
				<el-icon style="display: inline; vertical-align: middle"> <ele-Search /> </el-icon>
				<span>查询筛选</span>
			</div>
		</template>

		<el-form :model="queryParams" ref="queryForm" label-width="90">
			<el-row>
                <el-col :xs="12" :sm="12" :md="6" :lg="4" :xl="4" class="mb10">
                    <el-form-item label="时间">
                        <el-popover v-model:visible="timePopoverVisible" placement="bottom-start" :width="440" trigger="click">
                            <template #reference>
                                <el-input v-model="timeDisplay" placeholder="选择时间" readonly style="width:100%" />
                            </template>
                            <div class="time-panel">
                                <el-tabs v-model="tempPeriodType">
                                    <el-tab-pane label="月" name="month">
                                        <el-date-picker type="month" v-model="tempMonth" value-format="YYYY-MM" placeholder="选择月份" style="width: 100%" :disabled-date="() => false" @change="applyMonth" />
                                    </el-tab-pane>
                                    <el-tab-pane label="季" name="quarter">
                                        <div class="quarter-panel">
                                            <div class="quarter-year">
                                                <el-date-picker type="year" v-model="tempQuarterYear" value-format="YYYY" style="width: 120px" />
                                                <el-button size="small" @click="tempQuarterYear = String(new Date().getFullYear())">今年</el-button>
                                            </div>
                                            <div class="quarter-grid">
                                                <div class="quarter-card" :class="{ active: isSelectedQuarter(1) }" @click="pickQuarter(1)">一季度 <small>1-3月</small></div>
                                                <div class="quarter-card" :class="{ active: isSelectedQuarter(2) }" @click="pickQuarter(2)">二季度 <small>4-6月</small></div>
                                                <div class="quarter-card" :class="{ active: isSelectedQuarter(3) }" @click="pickQuarter(3)">三季度 <small>7-9月</small></div>
                                                <div class="quarter-card" :class="{ active: isSelectedQuarter(4) }" @click="pickQuarter(4)">四季度 <small>10-12月</small></div>
                                            </div>
                                        </div>
                                    </el-tab-pane>
                                    <el-tab-pane label="年" name="year">
                                        <el-date-picker type="year" v-model="tempYear" value-format="YYYY" placeholder="选择年份" style="width: 100%" @change="applyYear" />
                                    </el-tab-pane>
                                </el-tabs>
                            </div>
                        </el-popover>
                    </el-form-item>
                </el-col>

				<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6" class="mb10">
					<el-form-item label="延期状态">
						<el-select v-model="queryParams.planStart" placeholder="请选择状态" @change="handleQuery" style="width: 100%">
							<el-option :value="false" label="未完成" />
							<el-option :value="true" label="已完成" />
						</el-select>
					</el-form-item>
				</el-col>

				<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6" class="mb10">
					<el-form-item>
						<el-button-group style="display: flex; align-items: center">
							<el-button type="primary" icon="ele-Search" @click="handleQuery">查询</el-button>
							<el-button icon="ele-Refresh" @click="handleReset">重置</el-button>
							<el-button icon="ele-ZoomIn" @click="() => (showAdvanceQueryUI = true)" v-if="!showAdvanceQueryUI" style="margin-left: 5px">高级查询</el-button>
							<el-button icon="ele-ZoomOut" @click="() => (showAdvanceQueryUI = false)" v-if="showAdvanceQueryUI" style="margin-left: 5px">隐藏</el-button>
						</el-button-group>
					</el-form-item>
				</el-col>
			</el-row>

			<el-row v-if="showAdvanceQueryUI" class="advanced-query">
				<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6" class="mb10">
					<el-form-item label="分类">
						<el-select clearable filterable v-model="queryParams.className" placeholder="请选择分类" @change="handleQuery" style="width: 100%">
							<el-option v-for="(item, index) in dropdownData.className" :key="index" :value="item.value" :label="item.label" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6" class="mb10">
					<el-form-item label="区域">
						<el-select clearable filterable v-model="queryParams.workAreaId" placeholder="请选择区域" @change="handleQuery" style="width: 100%">
							<el-option v-for="(item, index) in dropdownData.workAreaId" :key="index" :value="item.value" :label="item.label" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6" class="mb10">
					<el-form-item label="关键词">
						<el-input v-model="queryParams.keyword" placeholder="请输入关键词" @keyup.enter="handleQuery" clearable />
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
	</el-card>
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from 'vue';

interface DropdownData {
	className: Array<{ value: number | null; label: string }>;
	workAreaId: Array<{ value: number | null; label: string }>;
}

interface QueryParams {
    workTime?: string; // 兼容保留
    periodType?: 'month'|'quarter'|'year';
    year?: string;
    quarter?: number;
    quarterMonth?: string;
    rangeStart?: string;
    rangeEnd?: string;
    className: number | null;
    workAreaId: number | null;
    keyword: string;
    planStart: boolean;
}

interface Props {
	dropdownData: DropdownData;
	initialQueryParams: QueryParams;
}

interface Emits {
	(e: 'query', params: QueryParams): void;
	(e: 'reset'): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const showAdvanceQueryUI = ref(false);
const queryParams = reactive<QueryParams>({ ...props.initialQueryParams });

// 格式化时间
const formatLocal = (date: Date): string => {
    const pad = (n: number) => String(n).padStart(2, '0');
    const yyyy = date.getFullYear();
    const MM = pad(date.getMonth() + 1);
    const dd = pad(date.getDate());
    const hh = pad(date.getHours());
    const mm = pad(date.getMinutes());
    const ss = pad(date.getSeconds());
    const ms = String(date.getMilliseconds()).padStart(3, '0');
    return `${yyyy}-${MM}-${dd}T${hh}:${mm}:${ss}.${ms}`;
};

// 计算范围（26→25）
const computeBusinessRange = () => {
    const type = queryParams.periodType || 'month';
    if (type === 'month') {
        const [y, m] = (queryParams.workTime || '').split('-').map((s) => parseInt(s, 10));
        if (!y || !m) return;
        const target = new Date(y, m - 1, 1);
        const prev = new Date(y, m - 2, 1);
        queryParams.rangeStart = formatLocal(new Date(prev.getFullYear(), prev.getMonth(), 26, 0, 0, 0, 0));
        queryParams.rangeEnd = formatLocal(new Date(target.getFullYear(), target.getMonth(), 25, 23, 59, 59, 999));
        return;
    }
    if (type === 'year') {
        const y = parseInt(queryParams.year || '', 10);
        if (!y) return;
        queryParams.rangeStart = formatLocal(new Date(y - 1, 11, 26, 0, 0, 0, 0));
        queryParams.rangeEnd = formatLocal(new Date(y, 11, 25, 23, 59, 59, 999));
        queryParams.workTime = `${y}-12`;
        return;
    }
    if (type === 'quarter') {
        if (queryParams.quarterMonth) {
            const [y, m] = queryParams.quarterMonth.split('-').map((s) => parseInt(s, 10));
            let start: Date, end: Date;
            if (m === 3) { start = new Date(y - 1, 11, 26, 0, 0, 0, 0); end = new Date(y, 2, 25, 23, 59, 59, 999); }
            else if (m === 6) { start = new Date(y, 2, 26, 0, 0, 0, 0); end = new Date(y, 5, 25, 23, 59, 59, 999); }
            else if (m === 9) { start = new Date(y, 5, 26, 0, 0, 0, 0); end = new Date(y, 8, 25, 23, 59, 59, 999); }
            else if (m === 12) { start = new Date(y, 8, 26, 0, 0, 0, 0); end = new Date(y, 11, 25, 23, 59, 59, 999); }
            else return;
            queryParams.rangeStart = formatLocal(start);
            queryParams.rangeEnd = formatLocal(end);
            queryParams.workTime = `${y}-${String(m).padStart(2, '0')}`;
            return;
        }
        const y = parseInt(queryParams.year || '', 10);
        const q = queryParams.quarter || 0;
        if (!y || !q) return;
        let start: Date, end: Date;
        if (q === 1) { start = new Date(y - 1, 11, 26, 0, 0, 0, 0); end = new Date(y, 2, 25, 23, 59, 59, 999); }
        else if (q === 2) { start = new Date(y, 2, 26, 0, 0, 0, 0); end = new Date(y, 5, 25, 23, 59, 59, 999); }
        else if (q === 3) { start = new Date(y, 5, 26, 0, 0, 0, 0); end = new Date(y, 8, 25, 23, 59, 59, 999); }
        else if (q === 4) { start = new Date(y, 8, 26, 0, 0, 0, 0); end = new Date(y, 11, 25, 23, 59, 59, 999); }
        else return;
        queryParams.rangeStart = formatLocal(start);
        queryParams.rangeEnd = formatLocal(end);
        queryParams.workTime = `${y}-${q === 1 ? '03' : q === 2 ? '06' : q === 3 ? '09' : '12'}`;
    }
};

// 统一显示
const timeDisplay = computed(() => {
    const cn = (q?: number) => q === 1 ? '一季度' : q === 2 ? '二季度' : q === 3 ? '三季度' : q === 4 ? '四季度' : '';
    if (queryParams.periodType === 'month' && queryParams.workTime) return `${queryParams.workTime}`;
    if (queryParams.periodType === 'quarter' && queryParams.year && queryParams.quarter) return `${queryParams.year} ${cn(queryParams.quarter)}`;
    if (queryParams.periodType === 'year' && queryParams.year) return `${queryParams.year}`;
    return '';
});

const timePopoverVisible = ref(false);
const tempPeriodType = ref<'month'|'quarter'|'year'>(queryParams.periodType || 'month');
const tempMonth = ref<string>('');
const tempYear = ref<string>('');
const tempQuarterYear = ref<string>(new Date().getFullYear().toString());

const pickQuarter = (q: number) => {
    const y = parseInt(tempQuarterYear.value || new Date().getFullYear().toString(), 10);
    const endMonth = q === 1 ? 3 : q === 2 ? 6 : q === 3 ? 9 : 12;
    queryParams.periodType = 'quarter';
    queryParams.year = String(y);
    queryParams.quarter = q;
    queryParams.quarterMonth = `${y}-${String(endMonth).padStart(2, '0')}`;
    computeBusinessRange();
    timePopoverVisible.value = false;
    handleQuery();
};

const applyMonth = (val: string) => {
    if (!val) return;
    queryParams.periodType = 'month';
    queryParams.workTime = val;
    computeBusinessRange();
    timePopoverVisible.value = false;
    handleQuery();
};

const applyYear = (val: string) => {
    if (!val) return;
    queryParams.periodType = 'year';
    queryParams.year = val;
    computeBusinessRange();
    timePopoverVisible.value = false;
    handleQuery();
};

const isSelectedQuarter = (q: number) => {
    if (queryParams.quarter && queryParams.year) return queryParams.quarter === q && queryParams.year === tempQuarterYear.value;
    if (queryParams.quarterMonth) {
        const [y, m] = queryParams.quarterMonth.split('-').map((s) => parseInt(s, 10));
        const endMonth = q === 1 ? 3 : q === 2 ? 6 : q === 3 ? 9 : 12;
        return String(y) === tempQuarterYear.value && m === endMonth;
    }
    return false;
};

const handleQuery = () => {
    emit('query', { ...queryParams });
};

const handleReset = () => {
    queryParams.className = null;
    queryParams.workAreaId = null;
    queryParams.keyword = '';
    queryParams.planStart = false; // 保持默认未完成
    // 重置时间为当前业务月
    const now = new Date();
    const day = now.getDate();
    const cur = day >= 26 ? `${now.getFullYear()}-${String(now.getMonth() + 2).padStart(2,'0')}` : `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2,'0')}`;
    queryParams.periodType = 'month';
    queryParams.workTime = cur;
    computeBusinessRange();
    emit('reset');
};
</script>

<style scoped lang="scss">
.query-form-card {
	background: var(--el-bg-color);
	border-radius: 12px;
	border: 1px solid var(--el-border-color-light);
	box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
	margin-bottom: 10px;
	transition: all 0.3s ease;

	&:hover {
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
		transform: translateY(-2px);
	}

	.card-header {
		display: flex;
		align-items: center;
		font-size: 16px;
		font-weight: 600;
		color: white;
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		border-radius: 8px 8px 0 0;
		padding: 15px 20px;
		margin: -20px -20px 20px -20px;
		gap: 8px;
	}
}

.advanced-query {
	margin-top: 15px;
	padding-top: 15px;
	border-top: 1px solid var(--el-border-color-lighter);
	background: var(--el-fill-color-lighter);
	border-radius: 8px;
	padding: 15px;
	margin-left: -15px;
	margin-right: -15px;
}

.mb10 {
	margin-bottom: 10px;
}

// 响应式设计
@media (max-width: 768px) {
	.query-form-card {
		margin-bottom: 15px;

		.card-header {
			padding: 12px 15px;
			margin: -15px -15px 15px -15px;
			font-size: 14px;
		}
	}

	.advanced-query {
		margin-left: -10px;
		margin-right: -10px;
		padding: 10px;
	}
}
</style>
<style scoped>
.time-panel { padding: 4px 0; }
.quarter-panel { display: flex; flex-direction: column; gap: 12px; }
.quarter-year { display: flex; align-items: center; gap: 8px; }
.quarter-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; }
.quarter-card { border: 1px solid var(--el-border-color); border-radius: 6px; padding: 12px 8px; text-align: center; cursor: pointer; background: linear-gradient(180deg, #f8fafc, #eef2f7); font-weight: 600; color: #303133; user-select: none; }
.quarter-card small { display:block; font-weight: 400; color: #909399; margin-top: 4px; }
.quarter-card:hover { border-color: var(--el-color-primary); box-shadow: 0 0 0 2px rgba(64,158,255,0.15) inset; }
.quarter-card.active { background: linear-gradient(180deg, #e8f3ff, #dbeafe); border-color: var(--el-color-primary); color: var(--el-color-primary); }
</style>
